package cn.mengfly.testnrz.im.server.handler;

import cn.mengfly.testnrz.im.ProtoMsg;
import cn.mengfly.testnrz.im.client.FutureTaskSchedule;
import cn.mengfly.testnrz.im.server.ServerSession;
import cn.mengfly.testnrz.im.server.processer.ChatRedirectProcesser;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author Mengfly
 */
@ChannelHandler.Sharable
public class ChatRedirectHandler extends ChannelInboundHandlerAdapter {

    private final ChatRedirectProcesser chatRedirectProcesser = new ChatRedirectProcesser();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType type = pkg.getType();
        if (!type.equals(chatRedirectProcesser.type())) {
            super.channelRead(ctx, msg);
            return;
        }
        // 判断是否登录
        ServerSession serverSession = ServerSession.getSession(ctx);
        if (null == serverSession || !serverSession.isLogin()) {
            System.out.println("用户尚未登录，不能发送消息");
            return;
        }
        FutureTaskSchedule.add(() -> chatRedirectProcesser.action(serverSession, pkg));
        super.channelRead(ctx, msg);
    }
}
